<?php
/**
 * Product Handler - Unified product operations (Create, Update, Delete)
 */
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';
requireAdmin();

$action = $_GET['action'] ?? 'list';
$product_id = $_GET['id'] ?? 0;

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? $_POST['action'] ?? '';
    
    try {
        switch($action) {
            case 'create':
                $result = $pdo->prepare("
                    INSERT INTO products (name, price, description, stock_quantity, image_url, is_featured, is_active) 
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");
                $result->execute([
                    $input['name'],
                    $input['price'],
                    $input['description'],
                    $input['stock_quantity'],
                    $input['image_url'],
                    $input['is_featured'] ?? 0,
                    $input['is_active'] ?? 1
                ]);
                echo json_encode(['success' => true, 'message' => 'Product created']);
                exit;
                
            case 'update':
                $result = $pdo->prepare("
                    UPDATE products 
                    SET name = ?, price = ?, description = ?, stock_quantity = ?, image_url = ?, is_featured = ?, is_active = ?
                    WHERE id = ?
                ");
                $result->execute([
                    $input['name'], $input['price'], $input['description'],
                    $input['stock_quantity'], $input['image_url'],
                    $input['is_featured'] ?? 0, $input['is_active'] ?? 1,
                    $input['id']
                ]);
                echo json_encode(['success' => true, 'message' => 'Product updated']);
                exit;
                
            case 'delete':
                $pdo->beginTransaction();
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM order_items WHERE product_id = ?");
                $stmt->execute([$input['id']]);
                if ($stmt->fetchColumn() > 0) {
                    $pdo->rollBack();
                    echo json_encode(['success' => false, 'message' => 'Product has orders']);
                } else {
                    $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
                    $stmt->execute([$input['id']]);
                    $pdo->commit();
                    echo json_encode(['success' => true, 'message' => 'Product deleted']);
                }
                exit;
        }
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        exit;
    }
}

// For GET requests, redirect to products page
header('Location: products.php');

